package com.sun.showcase.biz.basic.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sun.showcase.biz.basic.dao.ResourceInfoDao;
import com.sun.showcase.biz.basic.service.ResourceInfoService;
import com.sun.showcase.biz.basic.service.RoleInfoService;
import com.sun.showcase.biz.basic.service.UserResourceService;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.client.basic.domain.ResourceInfo;
import com.sun.showcase.client.basic.query.ResourceInfoQuery;
import com.sun.showcase.utils.LoginContextHolder;
import com.sun.showcase.utils.TreeNode;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
@Service("resourceInfoService")
@Transactional
public class ResourceInfoServiceImpl implements ResourceInfoService{
	@Autowired
	private ResourceInfoDao resourceInfoDao;
	@Autowired
	private UserResourceService userResourceService;
	@Autowired
	private RoleInfoService roleInfoService;
	
	public void setResourceInfoDao(ResourceInfoDao dao) {
		this.resourceInfoDao = dao;
	}

	public DataGrid datagrid(ResourceInfoQuery resourceInfoQuery) {
		DataGrid j = new DataGrid();
		Pager<ResourceInfo> pager  = find(resourceInfoQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<ResourceInfoQuery> getQuerysFromEntitys(List<ResourceInfo> resourceInfos) {
		List<ResourceInfoQuery> resourceInfoQuerys = new ArrayList<ResourceInfoQuery>();
		if (resourceInfos != null && resourceInfos.size() > 0) {
			for (ResourceInfo tb : resourceInfos) {
				ResourceInfoQuery b = new ResourceInfoQuery();
				BeanUtils.copyProperties(tb, b);
				resourceInfoQuerys.add(b);
			}
		}
		return resourceInfoQuerys;
	}

	private Pager<ResourceInfo> find(ResourceInfoQuery resourceInfoQuery) {
		Page<ResourceInfo> page = PageHelper.startPage(resourceInfoQuery.getPage().intValue(), resourceInfoQuery.getRows().intValue());
		
		List<ResourceInfo> list = resourceInfoDao.findList(resourceInfoQuery);
		Pager<ResourceInfo> pager = new Pager<ResourceInfo>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return pager;
		
	}
	


	public ResourceInfo add(ResourceInfoQuery resourceInfoQuery) {
		ResourceInfo t = new ResourceInfo();
		BeanUtils.copyProperties(resourceInfoQuery, t);
		t.setCreateBy(LoginContextHolder.get().getUserId());
	    t.setCreateDate(new Date());
		resourceInfoDao.save(t);
		resourceInfoQuery.setId(t.getId());
		return t;
		
	}

	public void update(ResourceInfoQuery resourceInfoQuery) {
		ResourceInfo t = resourceInfoDao.getById(resourceInfoQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(resourceInfoQuery, t);
	    	t.setModifiedBy(LoginContextHolder.get().getUserId());
		    t.setModifiedDate(new Date());
		}
	    
	    resourceInfoDao.update(t);
	}

	public void delete(java.lang.String[] ids) {
		if (ids != null) {
			for(java.lang.String id : ids){
				ResourceInfo t = resourceInfoDao.getById(id);
				if (t != null) {
					resourceInfoDao.deleteById(id);
					userResourceService.deleteByResource(id);//删除用户资源
					roleInfoService.delResourcceRole(id);//删除角色资源表数据
				}
			}
		}
	}

	public ResourceInfo get(ResourceInfoQuery resourceInfoQuery) {
		return resourceInfoDao.getById(resourceInfoQuery.getId());
	}

	public ResourceInfo get(String id) {
		return resourceInfoDao.getById(id);
	}

	
	public List<ResourceInfoQuery> listAll(ResourceInfoQuery resourceInfoQuery) {
	    List<ResourceInfo> list = resourceInfoDao.findList(resourceInfoQuery);
		List<ResourceInfoQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	@Cacheable(value="queryCache",key="'queryCache_'+#p0")
	public List<ResourceInfoQuery> findByUserID(String userId) {
		List<ResourceInfo> list = resourceInfoDao.findByUserId(userId);
		List<ResourceInfoQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	public Map<ResourceInfoQuery, List<ResourceInfoQuery>> getResourceByUserID(String userId) {

		Map<ResourceInfoQuery, List<ResourceInfoQuery>> resourceMap = new LinkedHashMap<ResourceInfoQuery, List<ResourceInfoQuery>>();
		//根据用户id 查询父菜单列表  左侧菜单使用
		List<ResourceInfo> listParent=resourceInfoDao.findParentByUserId(userId);
		
		List<ResourceInfoQuery> listParentQy =getQuerysFromEntitys(listParent) ;
		
		for(ResourceInfoQuery resorceQry:listParentQy){
			ResourceInfoQuery rsInfoQuery = new ResourceInfoQuery();
			rsInfoQuery.setUserId(userId);
			rsInfoQuery.setParentId(resorceQry.getId());
			//根据菜单ID 查询该菜单下的子菜单  左侧菜单使用
			List<ResourceInfo> listChild=resourceInfoDao.findChildByParentId(rsInfoQuery);
			List<ResourceInfoQuery> listChildQy =getQuerysFromEntitys(listChild) ;
			resourceMap.put(resorceQry, listChildQy);
		}
		return resourceMap;
	}

	@Override
	@Cacheable(value="resourceCache",key="'resourceCache_'+#p0")
	public List<ResourceInfoQuery> getResourceListByUserID(String userId) {
		//根据用户id 查询父菜单列表  左侧菜单使用
		List<ResourceInfo> listParent=resourceInfoDao.findParentByUserId(userId);
		
		List<ResourceInfoQuery> listParentQy =getQuerysFromEntitys(listParent) ;
		
		for(ResourceInfoQuery resorceQry:listParentQy){
			ResourceInfoQuery rsInfoQuery = new ResourceInfoQuery();
			rsInfoQuery.setUserId(userId);
			rsInfoQuery.setParentId(resorceQry.getId());
			//根据菜单ID 查询该菜单下的子菜单  左侧菜单使用
			List<ResourceInfo> listChild=resourceInfoDao.findChildByParentId(rsInfoQuery);
			resorceQry.setChilds(listChild);
		}
		return listParentQy;
	}

	@Override
	public List<TreeNode> findParentResource() {
		List<TreeNode> listnode = new ArrayList<TreeNode>();
		//获取所有类型为模块 状态为有效的  作为父资源
		List<ResourceInfo> listParent=resourceInfoDao.findParentResource();
		for(ResourceInfo resourceInfo:listParent){//循环父资源  给父资源添加子菜单
			TreeNode treeNode = new TreeNode();
			treeNode.setId(resourceInfo.getId());
			treeNode.setText(resourceInfo.getName());
			Set<TreeNode> s = buildChidNodes(resourceInfo.getId());
			treeNode.setChildren(s);
			treeNode.setState("closed");
			listnode.add(treeNode);
		}
		return listnode;
	}
	
	public Set<TreeNode> buildChidNodes(String parentId){//循环迭代所有子资源  直至没有子资源为止
		List<ResourceInfo> resourceList = this.getChildByPid(parentId);
		Set<TreeNode> ss = new LinkedHashSet<TreeNode>();
		for(int i=0; i < resourceList.size(); i++){
			ResourceInfo r = resourceList.get(i);
			TreeNode nodes = new TreeNode();
			nodes.setId(r.getId().toString());
			nodes.setText(r.getName());
			if(buildChidNodes(r.getId()).size()>0){
				nodes.setChildren(buildChidNodes(r.getId()));
				nodes.setState("closed");
			}
			ss.add(nodes);
		}
		return ss;
	}
	
	@Override
	public List<ResourceInfo> getChildByPid(String prentId) {//根据父资源id 获取子资源
		return resourceInfoDao.findChildResourceByparentId(prentId);
	}

	@Override
	@Cacheable(value="queryCache",key="#p0")
	public List<ResourceInfo> findByPersonResource(String userId) {
		return resourceInfoDao.findByPersonResource(userId);
	}
}
